from typing import List, Dict, Optional

from fastapi import APIRouter, HTTPException, Depends
from fastapi.params import Query

from backend.models.user_model import AdminRegister, User
from backend.utils.database import get_user_by_username, create_user, delete_user_and_records, \
    get_all_detection_records, get_all_users, get_today_detection_records_count
from backend.utils.permission import require_admin
from backend.utils.security import get_password_hash

router = APIRouter(
    prefix="/admin",
    tags=["admin"],
    responses={404: {"description": "Not Found"}},
)

# 管理员注册
@router.post("/register")
async def admin_register(user: AdminRegister):
    # 检查用户名是否重复
    if get_user_by_username(user.username):
        raise HTTPException(status_code=400, detail="用户名已存在")
    # 创建用户
    passwd_hash = get_password_hash(user.password)
    user_id = create_user(user.username, passwd_hash, user.email, user.role)
    return {"message": "管理员注册成功", "user_id": user_id, "role": user.role}

# 获取所有检测记录
@router.get("/records", dependencies=[Depends(require_admin)])
async def get_all_records(current_user: dict = Depends(require_admin)):
    try:
        records = get_all_detection_records()
        counts = get_today_detection_records_count()
        return {
            "records": records,
            "counts": counts
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取检测记录失败：{str(e)}")

# 获取所有用户信息
@router.get("/users", dependencies=[Depends(require_admin)])
async def get_users(current_user: dict = Depends(require_admin), role: Optional[str] =Query(None, description="筛选角色")):
    try:
        users = get_all_users(role_filter=role)
        # 统计用户数量
        total_users = len(users)
        # 统计不同角色的用户数量
        role_counts = {}
        for user in users:
            user_role = user.get('role')
            role_counts[user_role] = role_counts.get(user_role, 0) + 1
        return {
            "users": users,
            "statistics": {
                "total_users": total_users,
                "users_by_role": role_counts
            }
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取用户信息失败：{str(e)}")

# 删除用户
@router.delete("/users", dependencies=[Depends(require_admin)])
async def delete_user(username: str, current_user: dict = Depends(require_admin)):
    # print("删除用户：", username)
    target_user: User = get_user_by_username(username)
    # print("target_user", target_user)
    # 检查用户是否存在
    if not target_user:
        raise HTTPException(status_code=404, detail="用户不存在")
    # 检查是否想删除自己
    if target_user["username"] == current_user["sub"]:
        raise HTTPException(status_code=400, detail="不能删除自己")
    # 检查是否想删除管理员
    if target_user["role"] == "管理员":
        raise HTTPException(status_code=400, detail="不能删除管理员")
    # 删除用户
    result = delete_user_and_records(username)
    if not result:
        raise HTTPException(status_code=500, detail="删除用户失败")
    return result